package cn.devcat.sso.config.security.handler;


import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import cn.devcat.sso.config.exception.RequestLimitException;
import cn.devcat.sso.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 请求限制接口
 * @author huhailong
 *
 */
@Slf4j
public class SecurityLimitUtil {
	
	private static final Map<String,Long> loginIpCountMap = new HashMap<>(); //记录ip登录次数，用来限制频繁登录
	
	public static void checkRequestCount(HttpServletRequest request) throws RequestLimitException{
        String ipAddress = HttpUtil.getIpAddress(request);
        long currentTimeMillis = System.currentTimeMillis();
        Long loginLoginTime = loginIpCountMap.getOrDefault(ipAddress,currentTimeMillis);
        long loginCount = (loginLoginTime - currentTimeMillis)/1000;  //登录次数
        //如果一个IP连续操作频繁20次则限制其2小时后才可以继续操作
        if(loginCount > 20){
            log.info("ip:{},already into blacklist, it's will quit blacklist after two hours",ipAddress);
            loginIpCountMap.put(ipAddress,currentTimeMillis+1000*60*60*2);
            throw new RequestLimitException("您的操作涉嫌暴力请求，登录操作已被禁止2小时");
        }
        if(loginLoginTime > currentTimeMillis){
            loginIpCountMap.put(ipAddress,loginIpCountMap.getOrDefault(ipAddress,currentTimeMillis)+1000);
            log.info("ip:{},login count is too much, count:{}",ipAddress, loginCount);
            throw new RequestLimitException("登录操作频繁，请稍后再试");
        }else{
            loginIpCountMap.put(ipAddress,currentTimeMillis+1000);
        }
    }

}
